import os
import time
import zipfile


# 遍历文件夹
def get_file_name(file_dir):
    file_list = []
    for root, dirs, files in os.walk(file_dir, topdown=False):
        for file in files:
            # L.append(os.path.splitext(os.path.basename(file))) # 获取文件名和后缀
            file_list.append(file)
    return file_list


def zip2file_handler(zip_file, save_path, pwd=None):
    try:
        if pwd is None:
            zip_file.extractall(path=save_path)
        else:
            zip_file.extractall(path=save_path, pwd=pwd.encode('utf-8'))
        print(f'{zip_file}文件解压成功，密码:{pwd}')
        return True
    except:
        print(f'{zip_file}文件解压失败，密码:{pwd}')
        return False


# 解压文件
def unzip_files(file_path, save_path, pwd):
    with zipfile.ZipFile(file_path) as zip_file:
        zip2file_handler(zip_file, save_path, pwd)


zip_dir = r'F:\压缩文件zipfile\zipfile_dir'

zip_file_path = r'output/2022-02-09-09.zip'


def get_zip_file_info(files_path):
    start_time = time.time()
    error_list = []
    files = get_file_name(files_path)
    real_list = []
    for file in files:
        # for content in zip_files.infolist():# 获取zip压缩文件的相关信息
        #     print(content)
        try:
            zip_files = zipfile.ZipFile(os.path.join(files_path, file), mode='r')
            for name in zip_files.namelist():
                file_info = name.split('.')
                real_list.append({'zip_file': file, 'file_name': file_info[0], 'file_type': file_info[1]})
            zip_files.close()
        except:
            error_list.append(file)
    print(time.time() - start_time)
    print(error_list)


if __name__ == '__main__':
    get_zip_file_info('output')
